#include "RawImage.h"
#include "stb_image.h"

RawImage::RawImage(int width, int height) : Image(width, height) {
	colorBuffer = unique_ptr<Color[]>(new Color[width * height]());
}

RawImage::RawImage(string filename, float gamma, float scale) : Image(0, 0) {
	int comp = 0;
	stbi_ldr_to_hdr_scale(scale);
	stbi_ldr_to_hdr_gamma(gamma);
	float * data = stbi_loadf(filename.c_str(), &this->width, &this->height, &comp, STBI_rgb);
	colorBuffer = unique_ptr<Color[]>(new Color[width * height]());
	for (int x = 0; x < width; x++)
		for (int y = 0; y < height; y++) {
			int p = y * width + x;
			colorBuffer[p].r = data[3 * p];
			colorBuffer[p].g = data[3 * p + 1];
			colorBuffer[p].b = data[3 * p + 2];
		}
	delete[] data;
}

void RawImage::setColor(int x, int y, const Color &color) {
	colorBuffer[y * width + x] = color;
}

void RawImage::addColor(int x, int y, const Color &color) {
	colorBuffer[y * width + x] += color;
}

void RawImage::clearColor(int x, int y) {
	colorBuffer[y * width + x] = Colors::Black;
}

Color RawImage::getColor(int x, int y) const {
	return colorBuffer[y * width + x];
}

void RawImage::getColor(Color & color, int x, int y) const {
	color = colorBuffer[y * width + x];
}

Color RawImage::getOutputColor(int x, int y) const {
	Color color(colorBuffer[y * width + x]);
	toneMapping.map(color);
	return color.gammaCorrect_inv(oneOverGamma);
}

void RawImage::getOutputColor(Color & color, int x, int y) const {
	color = colorBuffer[y * width + x];
	toneMapping.map(color);
	color.gammaCorrect_inv(oneOverGamma);
}